package com.allqj;

import java.util.function.Supplier;

/**
 * @author sjw
 * @className Lazy
 * @date 2021/11/1 9:42
 * @description: TODO
 */
public class Lazy<T> implements Supplier<T> {

    private final Supplier<? extends T> supplier;

    // 利用 value 属性缓存 supplier 计算后的值
    private T value;

    private Lazy(Supplier<? extends T> supplier) {
        this.supplier=supplier;
    }



    @Override
    public T get() {
        if(value==null){
            System.out.println("=========rpc");
            T newValue=supplier.get();
            if(newValue==null)throw new IllegalStateException("Lazy value can not be null!");
            value=newValue;
        }
        return value;
    }


    public static <T> Lazy<T> of(Supplier<? extends T> supplier) {
        return new Lazy<>(supplier);
    }

    public static void main(String[] args) {
//        Supplier<Integer> a=()->{
//            System.out.println("get a");
//            return 10+1;
//        };
//        System.out.println("------------");
//        int b=a.get()+1;
//        System.out.println(b);

        Lazy<Integer> a= Lazy.of(()->{
            System.out.println("rpc");
            return 10+1;
        });
        System.out.println("----------------aa");
        int b= a.get()+1;
        int c= a.get()+1;
        System.out.println("----------------aa");
        System.out.println(b);
        System.out.println(c);

    }



}
